const Koa = require('koa');
const app = new Koa();
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors'); //跨域
const jwt = require('koa-jwt');
const allRoutes = require('./routes');
const {getInstance} = require("./utils/mysql-client")
const clickhouse = require("./utils/clickhouse-client")
//设置全局链接
global.idcSequelize = getInstance('idc');
global.clickhouse = clickhouse;
global._ = require('underscore');

//错误处理程序
onerror(app);

// middlewares
app.use(bodyParser());
app.use(json());
app.use(require('koa-static')(__dirname + '/public/'));

//密钥
const jwtSecret = "jwtSecret"

//进来校验jwt 是否在不在过期
app.use(function (ctx, next) {
    return next().catch((err) => {
        if (401 == err.status) {
            // ctx.status = 401;
            ctx.body = {code: 401, msg: '校验过期或校验失败'};
        } else {
            throw err;
        }
    });
});

// 配置白名单
app.use(jwt({secret: jwtSecret}).unless({path: [/^\/api\/loginInit/, /^\/api\/changeStatus/]}));

//允许请求跨域
app.use(cors({credentials: true}));

//错误处理
app.use(async (ctx, next) => {
    let start = new Date();
    let ms;
    try {
        ms = new Date() - start;
        await next();
        console.info(`${ctx.method} ${ctx.url} - ${ms}ms`);
    } catch (err) {
        ms = new Date() - start;
        if (err.errorCode) {
            console.log('捕获到错误');
            console.error(ctx, err, ms);
            return ctx.body = err.msg
        }
    }

});

// 使用路由
app.use(allRoutes.routes()).use(allRoutes.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app;
